package com.situ.personal.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.personal.entity.Province;
import com.situ.personal.util.JDBCUtil;

import net.sf.json.JSONArray;

@WebServlet("/selectArea")
public class SelectAreaServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		switch (method) {
		case "selectProvince":
			selectProvince(req, resp);
			break;

		default:
			break;
		}
	}

	private void selectProvince(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		ArrayList<Province> list = new ArrayList<Province>();
		// 加载驱动
		try { // DBUtils
			connection = JDBCUtil.getConnection();
			String sql = "select id,province from tm_province";
			preparedStatement = connection.prepareStatement(sql);
			System.out.println(preparedStatement);
			resultSet = preparedStatement.executeQuery();
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String province = resultSet.getString("province");
				Province pro = new Province(id, province);
				list.add(pro);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(resultSet, preparedStatement, connection);
		}
		for (Province province : list) {
			System.out.println(province);
		}
		
		JSONArray jsonArray = JSONArray.fromObject(list);
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().write(jsonArray.toString());
	
		
	}
}
